package burp.Utils;

import burp.BurpExtender;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class JsonUtils {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static Map<String, Object> parseJsonBody(String jsonStr) {
        if (jsonStr == null || jsonStr.isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            return mapper.readValue(jsonStr, new TypeReference<>() {
            });
        } catch (Exception e) {
            BurpExtender.getInstance().getCallbacks().printError("JSON parsing failed:  " + e.getMessage());
            return new HashMap<>();
        }
    }

    public static String mapToJson(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return "{}";
        }
        try {
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            LoggerUtils.error("JSON conversion failed: " + e.getMessage());
            return "{}";
        }
    }
}
